import React, { useEffect, useState } from 'react';
import cn from 'classnames';
import s from './style.module.less';
import i from '@/index.module.css';
import { filterNull } from '@/utils';
import moment from 'moment';
import { loginLog } from '~/API/index';
import { Pagination, Table, Tooltip, Input, Datetime, Loading } from '@knownsec/react-component';
export default function LoginLog({topExport, updateFlag}) {
  const dateFormat = 'YYYY-MM-DD';
  const today = ['', ''];
  const [now, setNow] = useState(today);
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [count, setCount] = useState(0);
  const [valueDict, setValueDict] = useState({
    start_date: '',
    end_date: '',
    ip: '',
    operator: '',
  });
  const columns = [
    { title: '操作人', key: 'operator', dataIndex: 'operator' },
    { title: '角色', key: 'group', dataIndex: 'group', render: (val) => val?.length?val.join('、'):'-'},
    { title: '登录IP', key: 'ip', dataIndex: 'ip' },
    {
      title: '登录时间',
      key: 'time',
      dataIndex: 'time',
      render: (val) => (val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
    { title: '详情', key: 'desc', dataIndex: 'desc' },
  ];
  const disabledate = (current) => {
    return current > moment();
  };
  const changeQuery = (val, t, imedia = false) => {
    if (t === 'module') {
      setModuleItem(val[0].value);
    }
    const obj = Object.assign({}, valueDict);
    if (t === 'module' || t === 'type' || t === 'action') {
      obj[t] = [].concat(val[0].value);
    } else if (t === 'time') {
      if (val) {
        setNow(val);
        obj.start_date = val[0].format(dateFormat);
        obj.end_date = val[1].format(dateFormat);
      } else {
        setNow(['', '']);
        obj.start_date = '';
        obj.end_date = '';
      }
    } else {
      obj[t] = String(val).trim();
    }
    setValueDict(obj);
    if (imedia) {
      searchItem(obj);
    }
  };
  const onSearchChange = (key, obj) => {
    let d = {}
    if(key === 'time'){
      d = filterNull(obj)
    }else{
      d = filterNull(valueDict)
      if(key)
        d[key] = ''
    }
    setPage(1);
    setPageSize(10);
    getTableData(1,10,d);
  };
  function getTableData(page, pageSize, data = {}) {
    data = filterNull(data)
    setLoading(true)
    const sdata = Object.assign({page: page, pageSize: pageSize}, data)
    loginLog('GET', sdata).then((res) => {
      setLoading(false);
      setTableData(res.data.data);
      setCount(res.data.count);
    });
  }
  useEffect(() => {
    getTableData(page, pageSize, valueDict);
  }, [updateFlag]);
  return (
    <div className={cn(s.loginlog)}>
      <div className={s.searchBox}>
        {topExport()}
        <div className={cn(s.searchRight, s.mb10)}>
          <Input
            pro
            placeholder="操作人"
            value={valueDict.operator}
            autoComplete={'off'}
            className="searchName search-button"
            search
            onSearch={onSearchChange}
            clear
            onChange={({value}) => {
              let obj = Object.assign({}, valueDict);
              obj.operator = value;
              setValueDict(obj);
              if (!value) {
                onSearchChange('operator');
              }
            }}
          ></Input>
          <Input
            pro
            placeholder="登录IP"
            value={valueDict.ip}
            autoComplete={'off'}
            className="searchName search-button"
            search
            onSearch={onSearchChange}
            clear
            onChange={({value}) => {
              let obj = Object.assign({}, valueDict);
              obj.ip = value;
              setValueDict(obj);
              if (!value) {
                onSearchChange('ip');
              }
            }}
          ></Input>
          <Datetime
            disabledDate={disabledate}
            className={cn(s.radiu)}
            value={now}
            onChange={(val) => {
              val = val || ['', '']
              setNow(val);
              let obj = Object.assign({}, valueDict);
              obj.start_date = val[0]?moment(val[0]._d).toJSON():'';
              obj.end_date = val[1]?moment(val[1]._d).toJSON():'';
              setValueDict(obj);
              onSearchChange('time', obj)
            }}
          />
        </div>
      </div>
      <div>
        <Table 
          columns={columns} 
          tableLoading={loading}
          loadingLabel=""
          data={tableData} />
      </div>
      <div className={cn(i.pt20, i.df, i.aic, i.jcfe, i.pb20)}>
        {count > 10 && <Pagination
          total={count}
          showQuickJumper={{ goButton: true }}
          showSizeChanger={true}
          showTotal={(total) => `共${total}条`}
          pageSizeOptions={['10', '20', '50']}
          current={page}
          onChange={(page,size) => {
            setPage(page)
            setPageSize(size)
            getTableData(page,size,valueDict)
          }}
        />}
      </div>
    </div>
  );
}
